const express = require('express');
const router = express.Router();
const random = require('string-random');
const bodyParser = require('body-parser');
const chinaTime = require('china-time');
const replySQL = require('../../db/replySQL')
const postSQL = require('../../db/postSQL')
const loginSQL = require('../../db/loginSQL')
router.post('/addpost', bodyParser.json(), (req, res) => {
    // 检查用户ID是否为空
    if (!req.body["userID"]
        || typeof req.body["userID"] != "number") {
        res.json({
            err: 1,
            message: '用户ID为空'
        })
    } else if (!req.body["title"]
        || typeof req.body["title"] != "string"
        || !req.body["title"].length) {
        res.json({
            err: 1,
            message: '主题为空'
        })
    } else if (!req.body["content"]
        || typeof req.body["content"] != "string"
        || !req.body["content"].length) {
        res.json({
            err: 1,
            message: '内容为空'
        })
    } else if (req.body["partitionID"] == undefined
        || req.body["partitionID"] == null
        || typeof req.body["partitionID"] != "number") {
        res.json({
            err: 1,
            message: '分区为空'
        })
    } else {
        let userID = req.body["userID"];
        let userName = req.body["userName"];
        let title = req.body["title"];
        var content = req.body["content"];
        let partitionID = req.body["partitionID"];
        let time = chinaTime('YYYYMMDD');
        loginSQL.getByID(userID, (result) => {
            var userStatus = result[0].userStatus
            if (userStatus == 0) {
                res.json({
                    err: 3,
                    message: '用户被封禁'
                })
            } else {
                replySQL.addFile(content, (filename) => {
                    postSQL.addpost(userID, title, filename, partitionID, time, (post, partition) => {
                        res.json({
                            err: 200,
                            message: '发帖成功',
                            postID: post.postID,
                            userID,
                            userName,
                            title,
                            filename,
                            partitionID,
                            partitionName: partition.partitionName,
                            partitionTime: partition.partitionTime,
                            lastTime: time,
                            replyNum: 0
                        })
                    })
                })
            }
        })
    }
})

module.exports = router;